import 'package:flutter/material.dart';
import 'page_state.dart';

class UniversalStateWrapper extends StatelessWidget {
  final PageState state;
  final Widget child;
  final String? errorMessage;
  final VoidCallback? onRetry;
  final Widget? loadingWidget;
  final Widget? emptyWidget;
  final Widget? errorWidget;

  const UniversalStateWrapper({
    super.key,
    required this.state,
    required this.child,
    this.errorMessage,
    this.onRetry,
    this.loadingWidget,
    this.emptyWidget,
    this.errorWidget,
  });

  @override
  Widget build(BuildContext context) {
    switch (state) {
      case PageState.loading:
        return loadingWidget ?? _buildLoadingWidget();
      case PageState.empty:
        return emptyWidget ?? _buildEmptyWidget();
      case PageState.error:
      case PageState.networkError:
      case PageState.permissionError:
        return errorWidget ?? _buildErrorWidget(context);
      case PageState.success:
        return child;
    }
  }

  Widget _buildLoadingWidget() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(),
          SizedBox(height: 16),
          Text('加载中...'),
        ],
      ),
    );
  }

  Widget _buildEmptyWidget() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.inbox, size: 64, color: Colors.grey),
          SizedBox(height: 16),
          Text('暂无数据'),
        ],
      ),
    );
  }

  Widget _buildErrorWidget(BuildContext context) {
    IconData icon;
    String title;
    String subtitle;

    switch (state) {
      case PageState.networkError:
        icon = Icons.wifi_off;
        title = '网络连接失败';
        subtitle = '请检查网络设置后重试';
        break;
      case PageState.permissionError:
        icon = Icons.lock;
        title = '权限不足';
        subtitle = '您没有访问此内容的权限';
        break;
      default:
        icon = Icons.error_outline;
        title = '加载失败';
        subtitle = errorMessage ?? '发生未知错误';
    }

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(icon, size: 64, color: Colors.red),
          const SizedBox(height: 16),
          Text(
            title,
            style: Theme.of(context).textTheme.titleLarge,
          ),
          const SizedBox(height: 8),
          Text(
            subtitle,
            style: Theme.of(context).textTheme.bodyMedium?.copyWith(
              color: Colors.grey[600],
            ),
            textAlign: TextAlign.center,
          ),
          if (onRetry != null) ...[
            const SizedBox(height: 24),
            ElevatedButton.icon(
              onPressed: onRetry,
              icon: const Icon(Icons.refresh),
              label: const Text('重试'),
            ),
          ],
        ],
      ),
    );
  }
}